<template>
	<view class="edit-address">
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<u--form labelPosition="left" :model="address" :rules="rules" ref="form">
			<u-form-item labelWidth="200rpx" required label="联系姓名" prop="name" borderBottom>
				<u--input v-model="address.name" border="none"></u--input>
			</u-form-item>
			<u-form-item labelWidth="200rpx" required label="联系电话" prop="phone" borderBottom>
				<u--input v-model="address.phone" border="none"></u--input>
			</u-form-item>
			<u-form-item labelWidth="200rpx" required label="选择城市" prop="addressCity" borderBottom ref="item">
				<u-cell class="selectCity" :title="address.city" :isLink="true" arrow-direction="down" @click="selectAddress"></u-cell>
				<u-picker :loading="isLoading" :show="showPicker" ref="uPicker" :columns="columns" @confirm="confirm" @change="changeHandler" @cancel="cancel"></u-picker>
			</u-form-item>
			<u-form-item labelWidth="200rpx" required label="详细地址" prop="info" borderBottom>
				<u--textarea v-model="address.info" placeholder="请输入详细地址" autoHeight ></u--textarea>
			</u-form-item>
			<u-form-item labelWidth="200rpx" label="是否默认" prop="default" borderBottom>
				<u-switch v-model="address.default"></u-switch>
			</u-form-item>
			<u-button type="success" :text="btnText" @click="changeAddress"></u-button>
		</u--form>
	</view>
</template>

<script>
export default {
	data() {
		return {
			address: {
				name: '',
				phone: '',
				info: '',
				city: '省-市-县',
				default: false
			},
			rules: {
				name: {
					type: 'string',
					required: true,
					message: '请填写姓名',
					trigger: ['blur']
				},
				addressCity: {
					validator: () => {
						if (this.address.city.length > 6) return true
						return false
					},
					message: '请选择地址',
					trigger: ['change','blur'],
				},
				info: {
					type: 'string',
					required: true,
					message: '请输入详细地址',
					trigger: ['blur'],
				},
				phone: [
					{
						required: true, 
						message: '请输入手机号',
						trigger: ['blur'],
					},
					{
						validator: (rule, value, callback) => {
							return uni.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						trigger: ['blur'],
					}
				]
			},
			showPicker: false,
			isLoading: false,
			columns: [ [],[] ],
			county: [],
			address_city: '省-市-县',
			frist_address: [],
			addressId: 0,
			btnText: '添加地址',
			isChange: false
		};
	},
	onLoad() {
		// 获取省级数据
		this.getCityData(0, (arr)=> {
			this.$refs.uPicker.setColumnValues(0, arr)
		})
		// 获取北京市数据
		this.getCityData(1, (arr, temp)=> {
			this.$refs.uPicker.setColumnValues(1, arr)
			this.county = temp
		})
		// 设置初始值
		const vuex_address = this.$store.state.vuex_address
		// 判断是修改还是添加地址
		if (vuex_address) {
			this.address.name = vuex_address.name
			this.address.phone = vuex_address.phone
			this.address.info = vuex_address.address
			this.address.city = `${vuex_address.province}-${vuex_address.city}-${vuex_address.county}`
			this.address.default = vuex_address.is_default ? true : false
			this.addressId = vuex_address.id
			this.frist_address = [vuex_address.province, vuex_address.city, vuex_address.county]
			this.btnText = '修改地址'
			this.isChange = true
		}
	},
	methods: {
		// 接收省市县数据
		async getCityData(id=0, callback) {
			const res = await uni.$u.http.get('/api/city', {
				params: {pid: id}
			})
			const temp = Object.values(res)
			const arr = temp.map(item => {
				return item.name
			})
			console.log(arr)
			callback(arr, temp)
			
			// return arr
		},
		// 多级选择器选择事件
		changeHandler(e) {
			const {
				columnIndex,
				value,
				values, // values为当前变化列的数组内容
				index,
				// 微信小程序无法将picker实例传出来，只能通过ref操作
				picker = this.$refs.uPicker
			} = e
			// console.log(e)
			// 当第一列值发生变化时，变化第二列对应的选项
			if (columnIndex === 0) {
				// picker为选择器this实例，变化第二列对应的选项
				// 获取二级市的数据
				this.isLoading = true
				this.getCityData(index+1, (arr, temp)=> {
					this.$refs.uPicker.setColumnValues(1, arr)
					this.county = temp
				})
				this.isLoading = false
			}else {
				// picker为选择器this实例，变化第三列对应的选项
				// 获取三级县的数据
				this.isLoading = true
				const id = this.county[index].id
				this.getCityData(id, (arr)=> {
					this.$refs.uPicker.setColumnValues(2, arr)
				})
				this.isLoading = false
			}
		},
		// 多级选择器点击确定事件
		confirm(e) {
			// 回调参数为包含columnIndex、value、values
			this.showPicker = false
			this.address.city = e.value.join('-')
			this.frist_address = e.value
		},
		// 多级选择器点击取消事件
		cancel() {
			this.showPicker = false
		},
		// 点击选择城市显示多级选择器
		selectAddress() {
			this.showPicker = true
		},
		// 提交修改地址
		changeAddress() {
			// 提交前先验证表单
			this.$refs.form.validate().then(async res => {
				const option = {
					name: this.address.name,
					address: this.address.info,
					phone: this.address.phone,
					province: this.frist_address[0],
					city: this.frist_address[1],
					county: this.frist_address[2],
					is_default: this.address.default ? 1 : 0
				}
				if (this.isChange) {
					// 更新地址
					await uni.$u.http.put('/api/address/'+this.addressId, option)
					// 设置默认地址
					// if (this.address.default) {
					// 	await uni.$u.http.patch(`/api/address/${this.addressId}/default`)
					// }
				}else {
					// 添加地址
					await uni.$u.http.post('/api/address', option)
				}
				// 跳转到上一个页面
				uni.$u.route({
					type: 'redirect',
					url: '/pages/profile/address/address'
				})
			}).catch(errors => {
			})
			
		}
	},
};
</script>

<style lang="scss" scoped>
	.edit-address {
		padding: 40rpx;
		.selectCity {
			width: 100%;
			.u-cell__body {
				padding-left: 0!important;
			}
		}
	}

</style>
